const { ipcRenderer } = require('electron')

class Index {
    constructor() {
        this.user = getItem("UserInfo")
        this.setting()
        this.sendMessage()
        this.emitEvent()
        this.onEvent()
    }

    emitEvent() {
        sc.emit('JoinRoom', this.user);
    }

    onEvent() {

        sc.on('ShakeMessage', data => {
            if (data.user_name == this.user.user_name) {
                this.renderSystemMessage(`你发送了一个窗口抖动`)
            } else {
                this.renderSystemMessage(`${data.user_name}给你发送了窗口抖动`)
            }
        })

        sc.on('WelcomeUser', data => {
            this.renderSystemMessage(data)
        })

        sc.on('ServerMessage', data => {
            this.renderMessage(data, "other")
        })

        sc.on('onLineUserList', data => {
            $(".c_right .title").text(`群成员 ${data.length}`)
            $(".c_right ul").empty()

            
            
            data.forEach(v => {

                if (v.user_name ==  this.user.user_name) {
                    this.user.level = v.level
                }

                $(".c_right ul").append(`
                    <li>
                        <div class="use">
                            <img src="${v.user_img}" alt="">
                            <span>${v.user_name}</span>
                        </div>
                        ${v.level == 3
                        ? ''
                        : `<i class="iconfont icon-yonghu ${v.level == 1 ? 'qz' : 'gly'}"></i>`
                    }
                        
                    </li>
                `)
            });

            console.log("得到在线用户数后的user:",this.user);
        })

        sc.on('uploadImgName', data => {
            data.message = `
                <img class="gif_img" src="http://127.0.0.1:3000/upload/${data.message}" alt="">
            `
            this.renderMessage(data, "other")
        })

        sc.on('openShake', () => {
            ipcRenderer.send('windowsShake')
        })

    }

    sendMessage() {
        var self = this;
        $(".input").keydown(function (event) {
            let { keyCode, ctrlKey } = event;
            if (keyCode == 13 && ctrlKey) {
                $(".input").append("<div><br></div>")
                self.moveEnd($(".input")[0],'end')

            } else if (keyCode == 13) {
                if ($(".input").html().length != 0) {
                    self.user.message = $(".input").html()
                    self.user.timestamp = timestamp()

                    sc.emit('sendMessage', self.user);
                    self.renderMessage(self.user, 'me')
                    $(".input").html("")
                }
                return false;
            }
        });
    }

    renderMessage(v, type, isImg) {
        var self = this;
        $(".c_left").append(`
            <li class="${type == "me" ? 'm_r' : '' } ">
                <div class="time">${format('hh:mm:ss',v.timestamp)}</div>
                <div class="item">
                    <img class="avatar" src="${v.user_img}" alt="">
                    <div class="text">
                        <div class="name">
                          ${
                            v.level == 3 
                            ? ''
                            : `<span class="${v.level == 1 ? 'tips_qz' : 'tips_gly'}">${v.level == 1 ? '群主' : '管理员'}</span>`
                          }
                          
                          <lb class="u_n">${v.user_name}</lb>
                        </div>
                        <div class="message ${isImg == "gif" ? 'noback' : ''}">${v.message}</div>
                    </div>
                </div>
            </li>
        `);

       
        $(".c_left .avatar").last().click(function() {
            self.user.clickUserName = $(this).parent().find(".u_n").text()
            sc.emit('socketShake', self.user)
        })
    }

    renderSystemMessage(text) {
        $(".c_left").append(`
            <li class="system_message">
                <span>${text}</span>
            </li>
        `)
    }

    moveEnd(el) {
        el.focus();
        var range = window.getSelection();
        range.selectAllChildren(el);
        range.collapseToEnd();
    }

    setting() {
        var self = this;


        $(".f_action i").click(function() {
            if ($(this).index() <= 3) {
                console.log(this);
                if ($(".menu").css("display") == "none") {
                    self.changeActive(
                        $(".menu_footer li").eq($(this).index())
                    )
                    $(".menu").show()
                } else {
                    if (
                        $(".menu_footer li").eq($(this).index())
                        .hasClass("active")
                    ) {
                        $(".menu").hide()
                    } else {
                        self.changeActive(
                            $(".menu_footer li").eq($(this).index())
                        )
                    }
                }
            }
        })

        $(".menu_footer li").click(function() {
            self.changeActive($(this))
        })

        for(let i = 0; i <= 274; i++) {
            $(".emote").append(`
                <img src="../img/icon/${i}fix@2x.png" alt="">
            `)
        }

        $(".emote img").hover(
            function () {
              $(this).attr({
                src: `../img/icon/${$(this).index()}@2x.gif`
              })
            },
            function () {
                $(this).attr({
                    src: `../img/icon/${$(this).index()}fix@2x.png`
                })
            }
        );

        $(".emote img").click(function() {
            $(".input").append(`
              <img class="emote_img" src="../img/icon/${$(this).index()}@2x.gif" alt="">
            `)
        })

        for(let i = 0; i <= 12; i++) {
            $(".gif").append(`
                <img class="gif_img" src="../img/gif/${i}.gif" alt="">
            `)
        }

        $(".gif img").click(function() {
            self.user.message = $(this).prop("outerHTML")
            self.user.timestamp = timestamp()

            sc.emit('sendMessage', self.user);
            self.renderMessage(self.user, 'me','gif')
        })

        $(".icon-tupian1").click(async function() {
            let path = await ipcRenderer.invoke('openFileSelect')
            console.log("你选择的文件路径未：", path);
            let base64url = await imgToBase64(path)
           
            self.user.message = `
                <img class="gif_img" src="${path}" alt="">
            `
            self.user.timestamp = timestamp()

            self.renderMessage(self.user, "me")

            sc.emit('uploadFile', {
                user:  self.user,
                base64: base64url,
                fileType: path.match(/\.(\w+)$/)[1]
            });

        })

        $(".icon-shake").click(function() {
            delete self.user.clickUserName
            sc.emit('socketShake', self.user)
        })

        $(".user img").attr({
            src: getItem("UserInfo").user_img
        })

        $(".user .name").text(getItem("UserInfo").user_name)
        $(".header .room_name").text(getItem("UserInfo").room_id)

       
    }

    changeActive(el) {
        el.addClass("active")
        .siblings()
        .removeClass("active")

        $(".menu_title").text(
            $(el).text()
        );

        $(".menu_list .menu_item").eq(
            $(el).index()
        ).addClass("active")
        .siblings()
        .removeClass("active")
    }
}

new Index()